<?php
/**
 * ################################################
 * #【Description】 订单接口，用户小程序订单数据处理
 * #【Author】 akon
 * #【Date】 2017年8月7日
 * ################################################
 */
namespace Shx\Controller;
use Think\Controller;

class OrderController extends Controller {
    /**
     * 支付状态(pay_status): 0-->未支付   1-->待支付   2-->取消支付  3-->支付失败  4-->已支付
     */
    /**
     * 加入购物车
     */
    public function addCart() {
        //1、接受数据
        $receive   = json_decode(file_get_contents('php://input'),true);
        $user_info  = M('user')->where(array('user_session'=>$receive['session']))->field('user_id')->find();
        $sql        = "SELECT * FROM shx_goods WHERE goods_id=".$receive['product_id'];
        $goods_info = M()->query($sql);
        $address    = M('address')->where(array('user_id'=>$user_info['user_id'],'is_default'=>1))->find();
        if($receive['flag'] == 1){          //添加订单
            $order_id = date('YmdHis');
            $orders = array(
                'order_id' => $order_id,
                'user_id'  => $user_info['user_id'],
                'pay_status'  => 0,                  //0 未支付
                'ship_status' => 0,
                'create_time' => time(),
                'amount' => $receive['product_count'] * $goods_info[0]['price']
            );
            if($address){
                $orders['receiver']   = $address['name'];
                $orders['ship_addr']  = $address['address'];
                $orders['ship_phone'] = $address['phone'];
            }
            $id = M('orders')->add($orders);
            $goods = M('goods')->where(array('goods_id'=>$receive['product_id']))->field('name,bn,price')->find();
            $order_items = array(
                'order_id' => $id,
                'sku'      => $goods['bn'],
                'name'     => $goods['name'],
                'price'    => $goods['price'],
                'num'      => $receive['product_count'],
                'discount_price' => 0,
                'status'   => 0
            );
            //验证？？？
            M('order_items')->add($order_items);
        }else{
            $order_id = $receive['order_id'];
            $id = true;

        }

        if(!$id){
            $res = array(
                'success' => 'false'
            );
        }else{
            $res = array(
                'success'  => 'true',
                'order_id' => $order_id,
                'address'  => $address,
                'amount' => sprintf('%.2f',$goods_info[0]['price']) * $receive['product_count'],
                'goods'    => array(
                    0 => array(
                        'images'   => 'http://www.shenhexin.com/'.explode('|',$goods_info[0]['small_pic'])[0],
                        'name'     => $goods_info[0]['name'],
                        'price'    => sprintf('%.2f',$goods_info[0]['price']),
                        'count'    => $receive['product_count'],
                        'tax_type' => $goods_info[0]['invoice']
                    )
                )
            );
        }
        exit(json_encode($res, JSON_UNESCAPED_SLASHES|JSON_UNESCAPED_UNICODE));

    }

    /**
     * 更新发票信息
     */
    public function updateInvoice(){
        $receive = json_decode(file_get_contents('php://input'),true);
        //验证？？？
        $id = M('orders')->where(array('order_id'=>$receive['order_id']))->setField('invoice',$receive['invoice']);
        //验证？？？
        if($id){
            $res = array(
                'status' => 1,
                'invoice' => $receive['invoice']
            );
        }else{
            $res = array(
                'status' => 0
            );
        }
        exit(json_encode($res, JSON_UNESCAPED_SLASHES|JSON_UNESCAPED_UNICODE));
    }

    /**
     *
     */

    public function selectInvoice(){
        $receive = json_decode(file_get_contents('php://input'),true);
        p($receive);
        $res = M('orders')->where(array('order_id'=>$receive['order_id']))->field('invoice')->find();
        if($res){
            exit(json_encode($res, JSON_UNESCAPED_SLASHES|JSON_UNESCAPED_UNICODE));
        }
    }

    /**
     * 订单写入
     */
    public function saveOrder(){
        $receive = json_decode(file_get_contents('php://input'),true);
        $info = $receive['order_info'];
        $order_sn = date('YmdHis');
        //收货地址
        $address = M('user_address')->where(array('address_id'=>$info['address_id']))->field('consignee,address,mobile')->find();
        $goods   = M('goods')->where(array('goods_id'=>$info['good_id']))->field('goods_name,goods_sn,market_price,shop_price,cost_price')->find();
        /**
         * 订单状态：
         * 前台规则：
         *      0 --> 取消支付
         *      1 --> 已支付
         * 这是目前的逻辑
         */
        $order_info = array(
            'order_sn' => $order_sn,
            'user_id'  => $info['user_id'],
            'order_status' => $info['order_status'],
            'pay_status'   => $info['pay_status'],
            'consignee'    => $address['consignee'],
            'address'      => $address['address'],
            'mobile'       => $address['mobile'],
            'invoice_title' => $info['invoice'],
            'goods_price'  => $info['amount'],           //目前默认没有邮费
            'shipping_price' => 0,                       //邮费
            'order_amount' => $info['amount'],          //应付款金额
            'total_amount' => $info['amount'],          //订单总金额
            'add_time'     => time(),
            'pay_time'     => time()
        );
        /**订单详情表**/
        $order_goods = array(
            'goods_id' => $info['good_id'],
            'goods_name' => $goods['goods_name'],
            'goods_sn' => $goods['goods_sn'],
            'goods_num'  => $info['good_count'],
            'market_price' => $goods['market_price'],
            'goods_price'  => $goods['shop_price'],
            'cost_price'   => $goods['cost_price'],

        );


        /**下订单**/
        $order_id = M('order')->add($order_info);
        if($order_id){
            $order_goods['order_id'] = $order_id;
            $order_goods_id = M('order_goods')->add($order_goods);
            if(!$order_goods_id){
                $res = array(
                    'status' => 0,
                    'msg'    => '系统错误，请稍后重试'
                );
            }
            $res = array(
                'status' => 1,
                'order_sn' => $order_sn
            );
        }else{
            $res = array(
                'status' => 0,
                'msg'    => '下订单失败'
            );
        }
        exit(json_encode($res, JSON_UNESCAPED_SLASHES|JSON_UNESCAPED_UNICODE));
    }

    /**
     * 获取订单列表
     */
    public function getOrderList(){
        $receive = json_decode(file_get_contents('php://input'), true);
        $sql = "SELECT a.order_sn,a.order_amount,a.pay_time,b.goods_name,b.goods_price,b.goods_num,c.original_img FROM shx_order a JOIN shx_order_goods b ON a.order_id=b.order_id JOIN shx_goods c ON b.goods_id=c.goods_id WHERE a.user_id=" . $receive['user_id'] . " AND pay_status=4";
        $data = M()->query($sql);
        if($data){
            foreach($data as $key=>$val){
                $temp[$key] = array(
                    'order_sn' => $val['order_sn'],
                    'order_amount' => $val['order_amount'],
                    'pay_time' => date('Y-m-d', $val['pay_time']),
                    'goods_name' => $val['goods_name'],
                    'goods_price' => $val['goods_price'],
                    'goods_num' => $val['goods_num'],
                    'original_img' => 'http://manager.shenhexin.com'.$val['original_img']
                );
            }
            $res = array(
                'status' => 1,
                'orders' => $temp
            );
        }else{
            $res = array(
                'status' => 0,
                'msg'    => '网络错误，请稍后重试'
            );
        }
        exit(json_encode($res, JSON_UNESCAPED_SLASHES|JSON_UNESCAPED_UNICODE));
    }
}